package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.GulimallEnum;
import com.atguigu.common.exception.GulimallException;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.es.EsContant;
import com.atguigu.gulimall.search.es.SkuEsModel;
import com.atguigu.gulimall.search.service.SkuSaveToEsService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SkuSaveToEsServiceImpl implements SkuSaveToEsService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public Boolean productUpToEs(List<SkuEsModel> skuEsModels) {
        //这是个请求桶，你可以认为它是可以一次性装很多请求的
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            //对于每条记录来说，我都需要一个插入请求对象
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(EsContant.ES_INDEX_PRODUCT);
            //给这次插入的对象设置id
            indexRequest.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            //转成json格式
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk =null;
       try {
            bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        }catch (Exception e){
            log.error("商品上架连接es出现异常:",e);
            throw new GulimallException(GulimallEnum.PRODUCT_UP_ERROR);
        }
        List<BulkItemResponse.Failure> collect = Arrays.asList(bulk.getItems()).stream().map((item) -> {
//            item.getFailure().getCause().printStackTrace();
            return item.getFailure();
        }).collect(Collectors.toList());
        log.error("出现了es插入商品异常{}:",collect);
        boolean b = bulk.hasFailures();
        return b;
    }
}
